#!/bin/bash
#测试用例调度脚本

source ./lib/lib.sh

clean_up() {
    if [ -d "$LOG_DIR" ]; then
        # 删除日志目录下的所有文件和子目录
        if rm -rf "$LOG_DIR"/*; then
            log_success "Logs cleaned up."
        else
            log_error "Failed to clean up logs in $LOG_DIR."
        fi
    else
        log_info "$LOG_DIR Log directory doesn't exist, no need to clean up."
    fi
}

run_test() {
    local test_file=$1
    log_info "Running test: $test_file" | tee -a "$LOG_FILE"
    # 使用更兼容的重定向方法
    bash "$test_file" >> "$LOG_FILE" 2>&1
    local status=$?
    if [ $status -ne 0 ]; then
        log_error "Test failed: $test_file" | tee -a "$LOG_FILE"
    else
        log_success "Test succeeded: $test_file" | tee -a "$LOG_FILE"
    fi
}


run_tests_in_directory() {
    local test_dir=$1
    local test_files=$(find "$test_dir" -mindepth 1 -type f -name '*_test.sh')
    for test_file in $test_files; do
        run_test "$test_file"
    done
    wait
}

usage() {
    echo "Usage: $0 -d <test_directory> [-t <test_script>] [-s <skip_test>] [-o <only_tags>] [-p] [-c]"
    echo "  -d  Directory containing test scripts."
    echo "  -t  Specific test script to run."
    echo "  -s  Test script to skip."
    echo "  -o  Only run tests with these tags."
    echo "  -p  Run tests in parallel."
    echo "  -c  Clean up logs."
    echo "  -h  Display this help message."
}

# 参数解析
skip_tests=()
only_tags=()
parallel=false
clean=false
test_directory=""
test_scripts=()

while getopts ":d:t:s:o:pch" opt; do
  case $opt in
    d) test_directory="$OPTARG" ;;
    t) test_scripts+=("$OPTARG") ;;
    s) skip_tests+=("$OPTARG") ;;
    o) only_tags+=("$OPTARG") ;;
    p) parallel=true ;;
    c) clean=true ;;
    h) usage; exit 0 ;;
    \?) echo "Invalid option: -$OPTARG" >&2; usage; exit 1 ;;
    :) echo "Option -$OPTARG requires an argument." >&2; usage; exit 1 ;;
  esac
done

# 主脚本
main() {
    # 如果传入了清理选项，则进行清理并退出
    if [ "$clean" = true ]; then
        log_info "Cleaning up logs and temporary files..."
        clean_up
        exit 0
    fi

    if [[ -z "$test_directory" ]]; then
        log_error "Test directory not specified."
        echo "Usage: $0 -d <test_directory> [-t <test_script>] [-s <skip_test>] [-o <only_tags>] [-p]"
        exit 1
    fi

    # 创建日志目录并清空旧日志
    clean_up
    mkdir -p "$LOG_DIR"
    > "$LOG_FILE"
    > "$REPORT_FILE"

    # 执行测试
    if [[ ${#test_scripts[@]} -eq 0 ]]; then
        log_info "Running all tests in directory: $test_directory"
        run_tests_in_directory "$test_directory"
    else
        for test_script in "${test_scripts[@]}"; do
            # 检查是否跳过
            if [[ " ${skip_tests[*]} " == *" $test_script "* ]]; then
                log_info "Skipping test: $test_script"
                continue
            fi
            # 检查标签过滤
            if [[ ${#only_tags[@]} -ne 0 ]]; then
                script_tags=$(grep -oP '#tags: \K(.+)' "$test_directory/$test_script")
                tag_matched=false
                for tag in "${only_tags[@]}"; do
                    if [[ " $script_tags " == *" $tag "* ]]; then
                        tag_matched=true
                        break
                    fi
                done
                if ! $tag_matched; then
                    log_info "Skipping test (tags not matched): $test_script"
                    continue
                fi
            fi
            if $parallel; then
                run_test "$test_directory/$test_script" &
            else
                run_test "$test_directory/$test_script"
            fi
        done
        if $parallel; then
            wait # 等待所有后台进程完成
        fi
    fi
}

main "$@"

# 输出汇总
total_tests=$(grep -c "Running test:" "$LOG_FILE")
total_success=$(grep -c "Test succeeded:" "$LOG_FILE")
total_failed=$(grep -c "Test failed:" "$LOG_FILE")
log_info "Total tests run: $total_tests, Total succeeded: $total_success, Total failed: $total_failed"

# 写入报告文件
{
    echo "Test Report"
    echo "========================="
    echo "Total tests run: $total_tests"
    echo "Total succeeded: $total_success"
    echo "Total failed: $total_failed"
    echo ""
    echo "Failed tests:"
    grep "Test failed:" "$LOG_FILE"
    echo ""
    echo "For more details, see: $LOG_FILE"
} > "$REPORT_FILE"

# 显示报告
cat "$REPORT_FILE"
